from datetime import datetime,timedelta
from pymongo import MongoClient,errors

class MongoTiebaListQueue:
    
    OUTSTANDING,PROCESSING,COMPLETE=range(3)

    def __init__(self,client=None,timeout=300):
        self.client=MongoClient('localhost',27017) if client is None else client
        self.db=self.client.cache
        self.timeout=timeout
    
    def __nonzero__(self):
        record=self.db.tiabalist.find_one(
            {'status':{'$ne':self.COMPLETE}}
        )
        return True if record else False

    # def push(self,url):

    #     try:
    #         self.db.pro

    def pop(self):

        record=self.db.tiabalist.find_and_modify(
            query={'status':self.OUTSTANDING},
            update={'$set':{'status':self.PROCESSING}}
        )
        # record=self.db.tiabalist.find_one()
        if record:
            return [record['_id'],record['name']]
        else:
            self.repair()
            raise KeyError()
    
    def peek(self):
        record=self.db.tiabalist.find_one({'status':self.OUTSTANDING})
        if record:
            return record['name']
    
    def complete(self,url):
        #print('yes:',url)
        self.db.tiabalist.update({'_id':url},{'$set':{'status':self.COMPLETE}})

    def uncomplete(self,url):
        print('no:',url)
        self.db.tiabalist.update({'_id':url},{'$set':{'status':self.OUTSTANDING}})

    def repair(self):
        record = self.db.tiabalist.find_and_modify(
            query={                
                'status': {'$ne': self.COMPLETE}
            },
            update={'$set': {'status': self.OUTSTANDING}}
        )
        if record:
            print('Released:', record['_id'])
    

    
